//
//  XXDate.swift
//  XXSwiftDemo
//
//  Created by admin on 2022/3/25.
//

import Foundation

public enum XXDateFormat : String {
    case Y = "yyyy"
    case YM = "yyyy-MM"
    case YMD = "yyyy-MM-dd"
    case YMDE = "yyyy-MM-dd EEE"
    case YMDHM = "yyyy-MM-dd HH:mm"
    case YMDHMS = "yyyy-MM-dd HH:mm:ss"
    case HMS = "HH:mm:ss"
    case HM = "HH:mm"
}

// 时间戳转成字符串
func to(timeStr timeInterval:Double, _ dateFormat:XXDateFormat = .YMDHMS) -> String {
    let date:Date = Date.init(timeIntervalSince1970: timeInterval)
    let formatter = DateFormatter.init()
    formatter.dateFormat = dateFormat.rawValue
    return formatter.string(from: date as Date)
}

// 字符串转时间戳
func to(timeInterval timeStr:String, _ dateFormat:XXDateFormat = .YMDHMS) -> Double {
    let format = DateFormatter.init()
    format.dateStyle = .medium
    format.timeStyle = .short
    format.dateFormat = dateFormat.rawValue
    let date = format.date(from: timeStr)
    return date?.timeIntervalSince1970 ?? 0
}
var sinceTimeInterval:Int64{
    return Int64(Date().timeIntervalSince1970)
}
func sinceTimeStr(_ dateFormat:XXDateFormat = .YMDHMS) -> String {
    let formatter = DateFormatter.init()
    formatter.dateFormat = dateFormat.rawValue
    return formatter.string(from: Date() as Date)
}
extension Date {
    var timeInterval:Int64{
        return Int64(self.timeIntervalSince1970)
    }
    func timeStr(_ dateFormat:XXDateFormat = .YMDHMS) -> String {
        let formatter = DateFormatter.init()
        formatter.dateFormat = dateFormat.rawValue
        return formatter.string(from: self as Date)
    }
   
}
